/* $Id: StringUtil.java,v 1.14 2006/09/15 14:10:53 gigabass Exp $
 *
 * Copyright (c) Guido Ludwig. All rights reserved.
 * Use is subject to license terms.
 */
package de.guidoludwig.jtm.util;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

/**
 * Some useful methods manipulating strings ...
 * 
 * @author <a href="mailto:jtrade@gigabss.de">Guido Ludwig</a>
 * @version $Revision: 1.14 $
 */
public final class StringUtil {



	public static List<String> stringToList(String newV) {
		List<String> list = new ArrayList<String>();
		if (isBlank(newV)) {
			return list;
		}
		String newValue = newV.trim().replaceAll("\r\n", "\r").replaceAll("\n",
				"\r");
		StringTokenizer tokenizer = new StringTokenizer(newValue.trim(), "\r");
		while (tokenizer.hasMoreTokens()) {
			list.add(tokenizer.nextToken().trim());
		}
		return list;
	}

	/**
	 * @param s
	 * @return an escaped String
	 */
	public static String sqlEscape(String s) {
		if (s == null) {
			return null;
		}
		return s.replaceAll("\'", "\\\\'").replaceAll("\"", "\\\\'")
				.replaceAll("\r", "\\\\r").replaceAll("\n", "\\\\n");
	}

	/**
	 * Appends trimmed value to the StringBuffer if value is not empty. Inserts
	 * a blank before value if StringBuffer is not empty and the last Character
	 * in the StringBuffer is not a newline character
	 * 
	 * @param buffer
	 * @param value
	 */
	public static void appendIfNotBlank(StringBuffer buffer, String value) {
		if (isBlank(value)) {
			return;
		}
		String current = buffer.toString();
		Character last = current.length() == 0 ? null : current.charAt(current
				.length() - 1);
		if (last != null) {
			char lastChar = last.charValue();
			if (current.length() > 0 && lastChar != '\n' && lastChar != '\r') {
				buffer.append(" ");
			}
		}
		buffer.append(value.trim());
	}

	/**
	 * Erase invalid filename characters
	 * 
	 * @param filename
	 * @return a filename which is valid
	 */
	public static String makeValidFilename(String filename) {
		if (filename == null) {
			return null;
		}
		String valid = filename.trim();
		if (isBlank(valid) || valid.equals("?")) {
			return "Unknown";
		}
		valid = valid.replaceAll(">", "-").replaceAll("<", "-").replaceAll("'",
				"").replaceAll("[[^\\w-()]*]", " ");
		while (valid != valid.replaceAll("  ", " ")) {
			valid = valid.replaceAll("  ", " ");
		}
		return valid.trim();
	}
	
	public static boolean isBlank(String s) {
		return s == null || s.trim().length() == 0;
	}
	
}
